import { ref } from 'vue'
import {playList} from '@/utils/beep.ts'
import {totalMesCount} from '@/utils/api/userInfo.ts'
// import { useMessageStore } from '@/stores/messageStore';
const socketWeb = ref()

export const connectWebsocket = (userId) => {

	disconnectWebsocket()


	socketWeb.value = uni.connectSocket({
		url: getApp().globalData.baseUrl + '/websocket/' + userId, //仅为示例，并非真实接口地址。
		success: (res)=>{
			console.log("连接成功",res)
			startHeart()
		},
		fail: (res) => {
			console.log("连接错误",res)
		}
	});


	socketWeb.value.onMessage(function (message) {
		console.log("收到服务器消息:", message)
		const msg = JSON.parse(message.data);
		const data=msg.msgData
	
		if ('redBack' === msg.msgType) {
			// #ifdef APP-PLUS
			uni.$emit('updateRedEnvelope', data.trendsId)
			// #endif
			//发红包消息表示这个墙墙有人发了红包
			//把对应墙墙的红包标识显示出来... {"code":"100","trendsId":"1854741350330200066"}
		}
		if ('headline' === msg.msgType) {
			uni.$emit('updateHeadLine', data)
		}
		if ('message' === msg.msgType) {
			// const messageStore = useMessageStore();
			// messageStore.refreshAllMessages({ msgType: data.msgType });
			console.log('收到消息')
			playList(["dididi"])
			uni.$emit('refreshMsg', data)
			// #ifdef APP-PLUS
			totalMesCount().then(res=>{
				plus.runtime.setBadgeNumber(res.data);
			})
			// #endif
		}
		if('freeMsg' == msg.msgType){
			uni.$emit('indexFreeMsg')
		}


	})
	socketWeb.value.onClose(function (res) {
		console.log("连接关闭:", res)
		clearHeart()
		if(res?.reason=='CLOSE_NORMAL'){
			connectWebsocket(userId)
		}
	})

}


export const disconnectWebsocket = () => {

	socketWeb.value?.close({
		success: function (res) {
			console.log("关闭socket成功")
			clearHeart()
		},
		fail: function (res) {
			console.log("关闭socket失败",res)
			clearHeart()
		}
	})

}

const timerHeart=ref()

const startHeart=()=>{
	
	timerHeart.value=setInterval(()=>{
		socketWeb.value?.send({
			data:'heart...',
			fail:function(res){
				console.log("心跳发送失败...",res)
				const userId=uni.getStorageSync('userInfo')?.userId
				if(userId){
					connectWebsocket(userId)
				}
			}
		})
	},30000)

}

const clearHeart=()=>{
	if(timerHeart.value){
		clearInterval(timerHeart.value)
	}
}